/*
* 成本中心报表存在一个或者多个，这里统一渲染
* */
import React from 'react';
import 'styles/data-center/report/graphic-report/cost-center-chart.scss';
import VScrollChartsV2 from 'components/template/graphic-report/vscroll-echarts';
import ReportWrapper from "components/template/graphic-report/report-wrapper"

@ReportWrapper
class CostCenterChart extends React.Component {
  constructor(props) {
    super(props);
    this.chartsRefs = [];

    this.state = {
      costCenters: [],
      data: [],
      options: [],
    }
  }

  //挂载组件到父级组件
  componentDidMount() {
    const { onRef, reportKey } = this.props;
    onRef && onRef({ ref: this, reportKey });
  }

  clickCostCenterItem = ({ active, item, chartIndex, reportKey }) => {
    this.props.onActivatedItemChange({ active, item, chartIndex, reportKey });
    if (item) {
      // 成本中心项选择时需要将其他项的值清除
      this.chartsRefs.forEach((refObj, index) => {
        const { ref } = refObj || {};
        if (index !== chartIndex) {
          ref && ref.clearActiveItemAndRedraw && ref.clearActiveItemAndRedraw();
        }
      })
    }
  };

  renderChartTitle = (options) => {
    let title = options ? options.title._text : "";
    return title
  }

  bindChartsRefs = (index) => {
    return (refObj) => {
      this.chartsRefs[index] = refObj;
    }
  };

  clearActiveItem = () => {
    this.chartsRefs.forEach((refObj) => {
      const { ref } = refObj || {};
      ref && ref.clearActiveItem && ref.clearActiveItem();
    })
  };

  //渲染单个成本中心
  renderSingleCostCenter = (item, index) => {
    let options = item.costCenterExpenseEntity;
    let dataLength = item.dataLength;
    let bindFn = this.bindChartsRefs(index);
    const { reportKey, cols } = this.props;
    return (
      <VScrollChartsV2
        hideBoxShadow
        isSubHead
        title={this.renderChartTitle(options)}
        options={options}
        cols={cols / 3}
        dataLength={dataLength}
        onActivatedItemChange={this.clickCostCenterItem}
        chartIndex={index}
        isFetchingData={this.props.isFetchingData}
        allowActivated={true}
        onRef={bindFn}
        reportKey={reportKey}/>
    )
  };

  render() {
    let { options } = this.props;
    return (
      <div className='cost-center-chart'>
        {options.map((item, index) => this.renderSingleCostCenter(item, index))}
      </div>
    )
  }
}

CostCenterChart.propTypes = {
  options: React.PropTypes.any,//渲染需要的数据
  onActivatedItemChange: React.PropTypes.any,//点击当前图表回调事件
  onRef: React.PropTypes.any,//挂载当前组
  reportKey: React.PropTypes.any,
  isFetchingData: React.PropTypes.bool,
  cols: React.PropTypes.number
};

CostCenterChart.defaultProps = {};

export default CostCenterChart;
